package cn.jeeweb.modules.monitor.controller;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.mapper.Wrapper;
import com.ff.bi.model.RptDimDataJson;
import com.ff.common.util.meta.DataFilterUtil;
import com.ff.common.util.meta.ReflectionUtil;
import com.ff.common.util.validate.ValidatorUtil;
import com.ff.common.web.json.BaseReqJson;
import com.ff.common.web.json.BaseRspJson;

import cn.jeeweb.core.common.controller.BaseCRUDController;
import cn.jeeweb.core.common.service.ICommonService;
import cn.jeeweb.core.query.data.QueryRequest;
import cn.jeeweb.core.query.data.Queryable;
import cn.jeeweb.core.query.data.Condition.Filter;
import cn.jeeweb.core.query.wrapper.EntityWrapper;
import cn.jeeweb.core.security.shiro.authz.annotation.RequiresPathPermission;
import cn.jeeweb.core.utils.StringUtils;
import cn.jeeweb.modules.monitor.entity.McMonitorCertificate;
import cn.jeeweb.modules.monitor.entity.McMonitorOrg;
import cn.jeeweb.modules.monitor.entity.McMonitorSensor;
import cn.jeeweb.modules.monitor.service.IMcMonitorCertificateService;
import cn.jeeweb.modules.monitor.service.IMcMonitorCollectionService;
import cn.jeeweb.modules.monitor.service.IMcMonitorDeviceService;
import cn.jeeweb.modules.monitor.service.IMcMonitorOrgService;
import cn.jeeweb.modules.supervise.entity.McProject;
import cn.jeeweb.modules.sys.entity.Dict;
import cn.jeeweb.modules.sys.entity.Organization;
import cn.jeeweb.modules.sys.entity.User;
import cn.jeeweb.modules.sys.service.IOrganizationService;
import cn.jeeweb.modules.sys.service.IUserService;
import cn.jeeweb.modules.sys.utils.DictUtils;
import cn.jeeweb.modules.sys.utils.UserUtils;

/**   
 * @Title: 监督检测机构
 * @Description: 监督检测机构
 * @author shawloong
 * @date 2017-10-05 22:28:45
 * @version V1.0   
 *
 */
@Controller
@RequestMapping("${admin.url.prefix}/monitor/mcmonitororg")
@RequiresPathPermission("monitor:mcmonitororg")
public class McMonitorOrgController extends BaseCRUDController<McMonitorOrg, String> {
	
	@Autowired
	private IMcMonitorCertificateService mcMonitorCertificateService;
	@Autowired
	private IOrganizationService organizationService;
	
	@Autowired IMcMonitorOrgService orgService;
	
	@Autowired IMcMonitorDeviceService deviceService;
	
	@Autowired IMcMonitorCollectionService collectionService;
	
	@Autowired IUserService userService;
	
	@Override
	public void preEdit(McMonitorOrg mcMonitorOrg, Model model, HttpServletRequest request, HttpServletResponse response) {
		//获取组织信息

		Organization org  =  organizationService.selectById(mcMonitorOrg.getId());
		if (org != null) {
			mcMonitorOrg.setOrg(mcMonitorOrg.getId());
			mcMonitorOrg.setName(org.getName());
		}
		 
		model.addAttribute("data",mcMonitorOrg);
		// 获得机构证书管理数据
		List<McMonitorCertificate> mcMonitorCertificateList = mcMonitorCertificateService.selectList(new EntityWrapper<McMonitorCertificate>(McMonitorCertificate.class).eq("monitor.id",mcMonitorOrg.getId()));
		model.addAttribute("mcMonitorCertificateList", mcMonitorCertificateList);
	}
	/**
	 * 保存数据之前
	 * 
	 * @param entity
	 * @param request
	 * @param response
	 */
	@Override
	public void preSave(McMonitorOrg mcMonitorOrg, HttpServletRequest request, HttpServletResponse response) {
	
		if(null == mcMonitorOrg.getTemplatePerm())
		{
			mcMonitorOrg.setTemplatePerm("");
		}
	}
	@Override
	public void preAjaxList(Queryable queryable, EntityWrapper<McMonitorOrg> entityWrapper, HttpServletRequest request,
			HttpServletResponse response) {
		// TODO Auto-generated method stub
		super.preAjaxList(queryable, entityWrapper, request, response);
		User user = UserUtils.getUser();
		
		entityWrapper.eq("type", request.getParameter("type"));

		if(!"admin".equals(user.getUsername()))
		{
			List<Organization> orgList = organizationService.getSubOrg(user.getOrganizationIds());
			List idList = DataFilterUtil.getFieldValueFromList(orgList, "id");
			idList.add(user.getOrganizationIds());
			entityWrapper.in("org", idList);
 		}
	}
 
	public String detail(Model model, HttpServletRequest request, HttpServletResponse response) {
		String id = UserUtils.getUser().getOrganizationIds();
		Queryable queryable = QueryRequest.newQueryable();
		queryable.addCondition("org", id);
		McMonitorOrg entity = commonService.get(queryable );
		
		preDetail(entity, model, request, response);
		model.addAttribute("data", entity);
 
		return display("detail");
	}
 
	@RequestMapping("/parent/list")
	@ResponseBody
	public BaseRspJson<List<McMonitorOrg>> getParentMonitor(@RequestBody BaseReqJson request)
	{
		BaseRspJson<List<McMonitorOrg>> rsp = new BaseRspJson<List<McMonitorOrg>>();
		
		String orgId = UserUtils.getUser().getOrganizationIds();
		Organization org = organizationService.selectById(orgId);
		
		
		Queryable queryable = this.GetFilterCondition(request);
		queryable.addCondition("orgParentId", org.getParentId());
		 
		List<McMonitorOrg> obj = this.commonService.listWithNoPage(queryable);
		rsp.setObj(obj);
  		return rsp;
	}
	
	/*****************统计相关*********************/
	@RequestMapping(value = "/statistics")
	public String sta(Model model, HttpServletRequest request, HttpServletResponse response) {
		
		return display("stacontent");
	}
	
	@RequestMapping(value = "/statistics/area")
	public String staByArea(Model model, HttpServletRequest request, HttpServletResponse response) {
		
		return display("staarea");
	}
	
	@RequestMapping(value = "/statistics/type")
	public String staByType(Model model, HttpServletRequest request, HttpServletResponse response) {
		
		return display("statype");
	}
	
	@RequestMapping("/statistics/by")
	@ResponseBody
	public BaseRspJson<List<RptDimDataJson>> loadStaistics(@RequestBody BaseReqJson request){
		// TODO Auto-generated method stub
		BaseRspJson<List<RptDimDataJson>> rsp = new BaseRspJson<List<RptDimDataJson> >();
		List<RptDimDataJson> dataList = new ArrayList<>();
  		String method = this.getObj(request,String.class);

		if ("type".equals(method)) {

			RptDimDataJson dataOrg = statisOrgByType();	
			dataOrg.setY_name("机构数量");
			dataList.add(dataOrg);
			
			RptDimDataJson datadevice = statisByCompanyType(deviceService);
			datadevice.setY_name("设备数量");
			dataList.add(datadevice);
			
			RptDimDataJson dataUser = statisByCompanyType(userService);
			dataUser.setY_name("人员数量");
			dataList.add(dataUser);
			
			
		} else if ("area".equals(method)) {
			String provinceVal = "";
			String cityVal = "";
			String dictrictVal = "";
			List<Filter> filters = request.getFilter();
			for (Filter f : filters) {
				if("province".equals(f.getProperty())){
					provinceVal = (String) f.getValue();
				}
				if("city".equals(f.getProperty())){
					cityVal = (String) f.getValue();
				}
				if("district".equals(f.getProperty())){
					dictrictVal = (String) f.getValue();
				}
			}
			RptDimDataJson dataOrg = statisOrgByArea(provinceVal, cityVal, dictrictVal);	
			dataOrg.setY_name("机构数量");
			dataList.add(dataOrg);
			
			Map<String,List<McMonitorOrg>> orgMap = getOrgMap(provinceVal, cityVal, dictrictVal);
			RptDimDataJson datadevice = statisByArea(deviceService, orgMap);
			datadevice.setY_name("设备数量");
			dataList.add(datadevice);
			
			RptDimDataJson dataUser = statisByArea(userService,orgMap);
			dataUser.setY_name("人员数量");
			dataList.add(dataUser);
		}
	
		rsp.setObj(dataList);
		
		return rsp;
	}
	
	private RptDimDataJson statisOrgByType() {
		
		
//		EntityWrapper<McMonitorOrg> entityWrapper1 = new EntityWrapper<McMonitorOrg>();
// 		entityWrapper1.setSqlSelect("count(1) as id, company_type as name");
// 		entityWrapper1.groupBy("company_type");
//		List<McMonitorOrg> dataList = orgService.selectList(entityWrapper1);
//		List<String> x_data =  (List<String>) DataFilterUtil.getFieldValueFromList(dataList, "name");
//
//		List<?> y_data =  DataFilterUtil.getFieldValueFromList(dataList, "id");
		
		//以上不能保证所有类型
		Wrapper<McMonitorOrg> wrapper = new EntityWrapper<McMonitorOrg>(McMonitorOrg.class);
		List<McMonitorOrg> orgList = orgService.selectList(wrapper);
 		Map<String,List<McMonitorOrg>> orgMap = DataFilterUtil.buildMapList("companyType", orgList);
	
		List<Dict> dictList =  DictUtils.getDictList("company_type");
		List<String> x_data =  (List<String>) DataFilterUtil.getFieldValueFromList(dictList, "label");
		List<String> y_data = new ArrayList<>();
		for (String type : x_data) {
			List<McMonitorOrg> temp = orgMap.get(type);
			if (temp == null) {
				y_data.add("0");
			} else {
				y_data.add(String.valueOf(temp.size()));
			}
			
		}

		RptDimDataJson obj = new RptDimDataJson();
		obj.setX_data(x_data);
		obj.setY_data(y_data);

		return obj;
	}
	
	private RptDimDataJson statisOrgByArea(String provinceVal, String cityVal, String dictrictVal) {
		RptDimDataJson obj = new RptDimDataJson();

		List<McMonitorOrg> dataList = null;
		List<?> x_data = null;
		List<?> y_data = null;

		
		
  		EntityWrapper<McMonitorOrg> entityWrapper1 = new EntityWrapper<McMonitorOrg>();

 		if (provinceVal == "" || provinceVal == null) {
 			entityWrapper1.setSqlSelect("count(1) as id, province as name");
 			entityWrapper1.groupBy("province");
 			

 		} else if (cityVal == "" || cityVal == null) {
 			entityWrapper1.setSqlSelect("count(1) as id, city as name");
 			entityWrapper1.eq("province", provinceVal);
 			entityWrapper1.groupBy("city");
 			
 		} else if (dictrictVal == "" || dictrictVal == null) {
 			entityWrapper1.setSqlSelect("count(1) as id, district as name");
 			entityWrapper1.eq("province", provinceVal);
 			entityWrapper1.eq("city", cityVal);
 			entityWrapper1.groupBy("district");
 		} else {
 			entityWrapper1.setSqlSelect("count(1) as id, district as name");
 			entityWrapper1.eq("province", provinceVal);
 			entityWrapper1.eq("city", cityVal);
 			entityWrapper1.eq("district", dictrictVal);
 		}
 		
 		dataList = orgService.selectList(entityWrapper1);
		x_data =  (List<String>) DataFilterUtil.getFieldValueFromList(dataList, "name");
		y_data =  DataFilterUtil.getFieldValueFromList(dataList, "id");

		
		obj.setX_data(x_data);
		obj.setY_data(y_data);
 
		
		return obj;
	}
	
	private RptDimDataJson statisByCompanyType(ICommonService service)
	{
		RptDimDataJson obj = new RptDimDataJson();
		
		EntityWrapper entityWrapper1 = new EntityWrapper<>();
 		entityWrapper1.setSqlSelect("count(1) as id , monitor_id as monitor_id");
 		entityWrapper1.groupBy("monitor_id");
		List<McMonitorSensor> dataList = service.selectList(entityWrapper1);
  		Map<String,McMonitorSensor> dataMap = DataFilterUtil.buildMap("monitorId", dataList);
 
  		
		Wrapper<McMonitorOrg> wrapper = new EntityWrapper<McMonitorOrg>(McMonitorOrg.class);
		List<McMonitorOrg> orgList = orgService.selectList(wrapper);
 		Map<String,List<McMonitorOrg>> orgMap = DataFilterUtil.buildMapList("companyType", orgList);
		
		List<String> y_data = new ArrayList<String>();
		
		List<Dict> dictList =  DictUtils.getDictList("company_type");
		List<String> x_data =  (List<String>) DataFilterUtil.getFieldValueFromList(dictList, "label");
		for(String e :x_data)
		{
			List<McMonitorOrg> subOrg = orgMap.get(e);
			int num = 0;
			if(!ValidatorUtil.isEmpty(subOrg))
			{
				for(McMonitorOrg org : subOrg)
				{
					Object temp = dataMap.get(org.getId());
					Object val = ReflectionUtil.getValueByFieldName(temp, "id");
					if(null != val)
					{
						num += Integer.valueOf(val.toString());
					}
					
				}
			}
 			y_data.add(String.valueOf(num));
		}
		
		obj.setX_data(x_data);
		obj.setY_data(y_data);
		return obj;
	}
	
	private Map<String,List<McMonitorOrg>> getOrgMap(String provinceVal, String cityVal, String dictrictVal) {
		Map<String,List<McMonitorOrg>> orgMap = null;
		Wrapper<McMonitorOrg> entityWrapper1 = new EntityWrapper<McMonitorOrg>(McMonitorOrg.class);
		List<McMonitorOrg> orgList;
		if (provinceVal == "" || provinceVal == null) {
			orgList = orgService.selectList(entityWrapper1);
			orgMap = DataFilterUtil.buildMapList("province", orgList);

 		} else if (cityVal == "" || cityVal == null) {
 			entityWrapper1.eq("province", provinceVal);
			orgList = orgService.selectList(entityWrapper1);
			orgMap = DataFilterUtil.buildMapList("city", orgList);
 			
 		} else if (dictrictVal == "" || dictrictVal == null) {
 			entityWrapper1.eq("province", provinceVal);
 			entityWrapper1.eq("city", cityVal);
			orgList = orgService.selectList(entityWrapper1);
			orgMap = DataFilterUtil.buildMapList("district", orgList);
 		} else {
 			entityWrapper1.eq("province", provinceVal);
 			entityWrapper1.eq("city", cityVal);
 			entityWrapper1.eq("district", dictrictVal);
			orgList = orgService.selectList(entityWrapper1);
			orgMap = DataFilterUtil.buildMapList("district", orgList);
 		}
		
		return orgMap;
	}
	
	private RptDimDataJson statisByArea(ICommonService service, Map<String,List<McMonitorOrg>> orgMap)
	{
		RptDimDataJson obj = new RptDimDataJson();
		
		EntityWrapper entityWrapper1 = new EntityWrapper<>();
 		entityWrapper1.setSqlSelect("count(1) as id , monitor_id as monitor_id");
 		entityWrapper1.groupBy("monitor_id");
		List<McMonitorSensor> dataList = service.selectList(entityWrapper1);
		//只是替代
  		Map<String,McMonitorSensor> dataMap = DataFilterUtil.buildMap("monitorId", dataList);
 
		
		List<String> y_data = new ArrayList<String>();
		
		//List<Dict> dictList =  DictUtils.getDictList("company_type");
		//List<String> x_data =  (List<String>) DataFilterUtil.getFieldValueFromList(dictList, "label");
		
		List<String> x_data = new ArrayList<>();
		for(String e :orgMap.keySet())
		{
			x_data.add(e);
			List<McMonitorOrg> subOrg = orgMap.get(e);
			int num = 0;
			if(!ValidatorUtil.isEmpty(subOrg))
			{
				for(McMonitorOrg org : subOrg)
				{
					Object temp = dataMap.get(org.getId());
					Object val = ReflectionUtil.getValueByFieldName(temp, "id");
					if(null != val)
					{
						num += Integer.valueOf(val.toString());
					}
					
				}
			}
 			y_data.add(String.valueOf(num));
		}
		
		obj.setX_data(x_data);
		obj.setY_data(y_data);
		return obj;
	}
}
